import 'package:flutter/material.dart';

class FunctionButtonGrid extends StatelessWidget {
  final List<Map<String, String>> functionList;
  final Function(String) onButtonPressed;
  final double containerHeight; // 父容器的高度

  FunctionButtonGrid({
    required this.functionList,
    required this.onButtonPressed,
    required this.containerHeight,
  });

  @override
  Widget build(BuildContext context) {
    // 计算每行显示的按钮数量
    int crossAxisCount = 2; // 每行 2 个按钮
    int rowCount = (functionList.length / crossAxisCount).ceil(); // 计算行数

    // 计算每行的高度
    double rowHeight = (containerHeight - (rowCount - 1) * 5) / rowCount; // 减去行间距

    return Column(
      children: List.generate(rowCount, (rowIndex) {
        // 计算当前行的按钮
        int startIndex = rowIndex * crossAxisCount;
        int endIndex = (rowIndex + 1) * crossAxisCount;
        if (endIndex > functionList.length) {
          endIndex = functionList.length;
        }
        var rowButtons = functionList.sublist(startIndex, endIndex);

        return Column(
          children: [
            SizedBox(
              height: rowHeight, // 设置每行的高度
              child: Row(
                children: rowButtons.map((function) {
                  return Expanded(
                    child: Padding(
                      padding: EdgeInsets.all(8.0), // 添加内边距
                      child: ElevatedButton(
                        onPressed: () {
                          onButtonPressed(function['key']!);
                        },
                        style: ElevatedButton.styleFrom(
                          backgroundColor: Colors.orange, // 按钮背景颜色
                          foregroundColor: Colors.white, // 按钮文字颜色
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(8.0), // 圆角
                          ),
                          minimumSize: Size(double.infinity, rowHeight), // 设置按钮的最小高度
                          padding: EdgeInsets.symmetric(vertical: 16), // 增加内边距
                        ),
                        child: Text(
                          function['value']!,
                          style: TextStyle(fontSize: 20), // 增大字体
                        ),
                      ),
                    ),
                  );
                }).toList(),
              ),
            ),
            // 添加行间距
            if (rowIndex < rowCount - 1) SizedBox(height: 5), // 行间距为 5 像素
          ],
        );
      }),
    );
  }
}